class ThingsController < ApplicationController
 before_filter :login_required, :except=>[:view,:search]
  def add
    return unless request.post?
    #判断事件是否存在
    thing_tmp  = Thing.find_by_title(params[:thing]["title"])
    if thing_tmp.nil?
      thing_tmp = Thing.create(params[:thing])
    end
    #用户是否创建过此事
    if Thingsuser.find(:first,:conditions=>["user_id=? and thing_id=?",current_user.id,thing_tmp.id])
      flash[:notice] = "你以创建过此事"
      redirect_to "/things/view/#{thing_tmp.id}"
    else
        u_t = Thingsuser.new()
        u_t.user_id = current_user.id
        u_t.thing_id = thing_tmp.id
        if u_t.save
          flash[:notice] = "创建“#{thing_tmp.title}”成功"
          redirect_to "/things/view/#{thing_tmp.id}"
        end
    end
  end

  def destroy
  end

  def view

    id = params[:id]
    @thing = Thing.find(id)
    @application_description = @thing.title
    @user_lists = User.find(:all,:order=>"created_at desc",:limit=>10)
    @top_things = Thing.find(:all,:order=>"created_at desc",:limit=>10)
    @users = Thingsuser.find(:all,:conditions=>["thing_id=?",id])

    @tags = @thing.tag_list
  end

  def search
    str = params[:id]
    type = params[:type]
    user = params[:user]
    @user = User.find_by_login(user)
    if type == "t"
      str = str.split("-")
      @results = Thingsuser.paginate :page => params[:page],:per_page=>10,:conditions=>["YEAR(updated_at) = ? and MONTH(updated_at)=? and DAY(updated_at)=? ",str[0],str[1],str[2]]
    else
       @results = Thing.paginate :page => params[:page],:per_page=>10,:conditions=>["title like ?","%#{str}%"]
       puts "********************"
    end
  end

  def global_search
    @things = Thing.find_by_contents(params[:condition])
  end
end
